<template>
	<view class="fixed search top" style="z-index: 5;background-color: aliceblue;height: 10vh;">
		<view class="action" @click="goback" style="z-index: 20;">
			<text class="cuIcon-back text-gray"></text>
		</view>
		<view class="center-content">
			<view class="top_right">
				<view class="cu-avatar round" :style="{ 'background-image': 'url(' + otheravator + ')' }"></view>
			</view>
			<view class="content" style="text-align: center;">
				{{ title }}
			</view>
		</view>
	</view>
	<scroll-view class="contain bg-white" :scroll-into-view="'mes_' + (messageList.length-1)" scroll-y="true"
		@scroll="inscroll" ref="contain">
		<view class="more" v-show="more" @click="gethistory">
			{{ mo_con }}
		</view>
		<view class="cu-chat item" v-for="(item, index) in messageList" :id="`mes_${index}`" :ref="`mes_${index}`"
			:key="index">
			<view class="cu-item self" v-if="item.type == 0" style="z-index: 0;">
				<view class="main">
					<view class="content light bg-cyan shadow">
						<text>{{ item.content }}</text>
					</view>
				</view>
				<view class="cu-avatar radius" :style="{ 'background-image': 'url(' + myavator + ')' }">
				</view>
				<view class="date time">{{ item.time }}</view>
			</view>

			<view class="cu-item self" v-else-if="item.type == 1" style="z-index: 0;">
				<view class="main">
					<image :src="item.content" class="radius" mode="widthFix"></image>
				</view>
				<view class="cu-avatar radius" :style="{ 'background-image': 'url(' + myavator + ')' }">
				</view>
				<view class="date time">{{ item.time }}</view>
			</view>


			<view class="cu-item" v-else-if="item.type == 2" style="z-index: 0;">
				<view class="cu-avatar radius" :style="{ 'background-image': 'url(' + otheravator + ')' }">
				</view>
				<view class="main">
					<view class="content light bg-blue shadow">
						<text>{{ item.content }}</text>
					</view>
				</view>
				<view class="date  time"> {{ item.time }}</view>
			</view>

			<view class="cu-item" v-else-if="item.type == 3" style="z-index: 0;">
				<view class="cu-avatar radius" :style="{ 'background-image': 'url(' + otheravator + ')' }">
				</view>
				<view class="main">
					<image :src="item.content" class="radius" mode="widthFix"></image>
				</view>
				<view class="date time"> {{ item.time }}</view>
			</view>






			<view v-else-if="item.type == 4" class="invite_card"
				style="width: 100%;display: flex; justify-content:center;height:  150px;margin-bottom: 20px; ">
				<view
					style="width: 80%;display: flex;justify-content: center;align-items: center;flex-direction: column;background-image: url('https://obscloud.ulearning.cn/resources/web/17138806545708413.jpg');background-size: cover;background-repeat: no-repeat;border-radius: 20px;"
					class="card">
					<view style="color: #fff;font-size: 1rem;font-weight: 500;margin-bottom: 10px;margin-left: 30px;"
						class="title"> {{ item.content }}

					</view>
					<view style="margin-left: 30px;" class="btn">
						<view style="display: flex!important;margin-left: 100px;" class="btns" v-if="item.OK == 0">
							<!-- 别人发的 -->
							<view style="margin: 0; padding: 0;" class="status cu-item text-red" @click="Agree(item)">
								<view class="action">
									<view style="width:4rem;height: 2rem;"
										class="cu-tag lg round bg-gradual-green light">同意</view>
								</view>
							</view>
							<view style="margin: 0; padding: 0;" class="status cu-item text-red" @click="Refuse(item)">
								<view class="action">
									<view style="width: 4rem;height: 2rem;padding: 0!important;"
										class="cu-tag lg round bg-gradual-red light">拒绝</view>
								</view>
							</view>

							<!-- <button class="cu-btn bg-green round shadow" @click="Agree(item)">同意</button>
					<button class="cu-btn bg-red round shadow" @click="Refuse(item)">拒绝</button> -->
						</view>
						<view class="isok" v-else-if="item.OK == 1" style="color: greenyellow;">
							<view class="cu-tag round bg-gradual-green light">匹配完成√</view>
						</view>
						<view class="isok" v-else-if="item.OK == 2" style="color: red;">
							<view class="cu-tag round bg-red light">匹配失败×</view>
						</view>
						<view class="isok" v-else-if="item.OK == 3" style="color: black;">
							<view class="cu-tag round bg-gradual-red light">等待对方回应</view>
						</view>
						<view class="isok" v-else-if="item.OK == 4" style="color: black;">
							<view class="cu-tag round bg-gradual-red light">已经过期</view>
						</view>
					</view>
				</view>



			</view>
			<view class="invite" v-else-if="item.type == 4">
				<view class="title">
					邀请
				</view>
				<view class="content">
					{{ item.content }}
				</view>
				<view class="btns" v-if="item.OK == 0"><!-- 别人发的 -->
					<view class="status cu-item text-red" @click="Agree(item)">
						<view class="action">
							<view class="cu-tag lg round bg-gradual-green light">同意</view>
						</view>
					</view>
					<view class="status cu-item text-red" @click="Refuse(item)">
						<view class="action">
							<view class="cu-tag lg round bg-gradual-red light">拒绝</view>
						</view>
					</view>

					<!-- <button class="cu-btn bg-green round shadow" @click="Agree(item)">同意</button>
					<button class="cu-btn bg-red round shadow" @click="Refuse(item)">拒绝</button> -->
				</view>
				<view class="isok" v-else-if="item.OK == 1" style="color: greenyellow;">
					<view class="cu-tag round bg-gradual-green light">匹配完成√</view>
				</view>
				<view class="isok" v-else-if="item.OK == 2" style="color: red;">
					<view class="cu-tag round bg-red light">匹配失败×</view>
				</view>
				<view class="isok" v-else-if="item.OK == 3" style="color: black;">
					<view class="cu-tag round bg-gradual-red light">等待对方回应</view>
				</view>
				<view class="isok" v-else-if="item.OK == 4" style="color: black;">
					<view class="cu-tag round bg-gradual-red light">已经过期</view>
				</view>
			</view>






		</view>
	</scroll-view>
	<view class="bott {{InputBottom!=0?'cur':''}}" style="bottom:{{InputBottom}}px;">
		<view class="tools foot">

			<view class="status cu-item text-red tool" @click="getimg">
				<view class="action">
					<view class="cu-tag  round line-gradual-green light"><text class=" iconfont icon-tupian"></text>
					</view>
				</view>
			</view>
			<view class="status cu-item text-red tool" @click="postInvite">
				<view class="action">
					<view class="cu-tag  round line-gradual-green light"><text class=" iconfont icon-woshou"
							@click="postInvite"></text></view>
				</view>
			</view>

		</view>

		<view class="foot cu-bar" style="display: flex;justify-content: space-evenly;">
			<input placeholder="" type="text" name="text" :adjust-position="true" cursor-spacing="15" class="input"
				v-model="msg">
			<button class="cu-btn bg-green shadow" @click="sendMsg"
				style="margin-right:10px;display: inline-block;width: 5vw;display: flex;align-items: center;margin-left: 4px;">发送</button>
		</view>
		<!-- 		<view class="foot cu-bar" style="display: flex;justify-content: space-evenly;">
			<input placeholder="" type="text" name="text" :adjust-position="true" cursor-spacing="15" class="input"
				v-model="msg">
			<button class="cu-btn bg-green shadow" @click="sendMsg" style="margin-right:5px;">发送</button>
		</view> -->
	</view>
	<drawer class="drawers"></drawer>
</template>
<style scoped lang="less">
	@import url('../../static/chat_icon/iconfont.css');

	.input {
		width: 30vw;
		height: 45px;
		padding: 12px;
		border-radius: 12px;
		border: 1.5px solid lightgrey;
		outline: none;
		transition: all 0.3s cubic-bezier(0.19, 1, 0.22, 1);
		box-shadow: 0px 0px 20px -18px;
	}

	.input:hover {
		border: 2px solid lightgrey;
		box-shadow: 0px 0px 20px -17px;
	}

	.input:active {
		transform: scale(0.95);
	}

	.input:focus {
		border: 2px solid grey;
	}








	.center-content {
		margin-left: -30px;
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	@media screen and (min-width: 600px) {
		.cu-bar {
			width: 35vw;
		}
	}

	.cu-bar {
		position: fixed;
	}

	.centered-view {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.vie {
		position: absolute;
		top: 50%;
		left: 50%;
	}

	.isok {
		width: 100%;
		text-align: center;
		color: red;
	}

	.contain {
		height: 90vh !important;
		padding-bottom: 10vh;

	}

	.top {
		height: 5vh;
		padding-top: 2vh;
		padding-bottom: 2vh;
		// line-height: 15vh;
		display: flex;
		align-items: center;
		width: 100%;
		// justify-content: space-between;
		// align-items: center;
		padding-left: 3vh;
		padding-right: 3vh;
	}


	.more {
		margin-top: 10px;
		width: 100%;
		font-size: 12px;
		text-align: center;
	}

	.iconfont {
		font-size: medium;
	}

	.bg {
		background-size: cover;
		background-repeat: no-repeat;
		background-position: center;
	}

	.time {
		color: black !important;
	}

	.tools {
		// width: 100%;
		// height: 8vh;
		// border: 1px solid black;
		position: absolute;
		bottom: 8vh;
		display: flex;
		// background-color: ghostwhite;
		// border-top-left-radius: 10px;s
		// border-top-right-radius: 10px;

		// display: flex;
		.tool {
			// border: 0.1px solid black;
			// border-radius: 4px;
			// height: 5vh;
			line-height: 5vh;
			margin-left: 10px;
			font-size: 40rpx;

		}
	}

	.drawers {
		z-index: 100;
	}

	.invite {
		width: 70%;
		// background-color: aliceblue;
		margin: 10px auto;

		border-radius: 10rpx;
		padding-top: 3vh;
		padding-bottom: 3vh;
		box-shadow: 1px 3px 5px 3px #888888;
		background-color: #fefefe;


		.title {
			width: 100%;
			text-align: center;
			font-weight: 700;
		}

		.content {
			margin: 10px auto;
			text-align: center;
			max-width: 70%;
		}

		.btns {
			width: 100%;
			display: flex !important;
			;
			justify-content: space-evenly;
			flex-direction: row;
			// margin-bottom: 7px;
		}

		.uni-view {}
	}
</style>
<script>
	import drawer from '@/modul/Chat/drawer.vue'
	import {
		getuserInfo,
		uploadimg,
		getHistory,
	} from '@/store/api.js'
	export default {
		components: {
			drawer
		},
		data() {
			return {
				ifclose: true,
				title: '',
				mo_con: '查看更多',
				ifFrist: true,
				more: false,
				myavator: '',
				otheravator: '',
				topimg: '',
				bot: '',
				scrollTop: 0,
				scrollHeight: 0,
				clientHeight: 0,
				mes_top: '更多历史',
				iflower: false,
				iffrist: true,
				if_more: true,
				userid: '',
				token: '',
				bottom: 0,
				scrollTop: 0,
				showList: false,
				InputBottom: 300,
				msg: '',
				socket: null,
				messageList: [], //0是我的文字，1是我的图片，2是对方文字，3是对方图片，4是进出
				rebackMes: []
			};
		},
		onUnload() {
			uni.$off('Look')
			uni.$off('backkk')

		},
		onLoad(value) {
			getuserInfo().then(res => {
				console.log(res)
				this.myavator = res.data.avatar
			})
			console.log('聊天页面接收到的item:', value);
			this.title = value.name
			this.otheravator = value.src
			this.userid = value.userid
		},
		mounted() {
			uni.$on('Look', values => {
				console.log('收到发过来的信息了')
				console.log(values)
				if (this.messageList.find(item => item.sendTime == values.mes.timestamp)) {
					this.messageList.find(item => item.sendTime == values.mes.timestamp).uuid = values.mes.uuid
				}
				if (values.mes.sendFrom == this.userid) { //对方消息
					if (values.mes.content.startsWith('**/img/**')) { //对方图片
						this.messageList.push({
							type: 3,
							content: values.mes.content.substring(9),
							time: this.formatDateTime(values.mes.timestamp),
							sendTime: values.mes.timestamp,
							uuid: values.uuid
						})
					} else if (values.type == 4) {
						this.messageList.push({
							uuid: values.uuid,
							type: 4,
							content: values.mes.content.split('**/img/**')[0],
							postId: values.mes.postId,
							OK: 0,
							time: this.formatDateTime(values.mes.timestamp),
							sendTime: values.mes.timestamp
						})
					} else if (values.type == 2 || values.type == 3) {
						let cu = values.mes.content.split('**/uuid/**');
						this.findLast(item => item.type == 4 && item.content == cu[0] && item.uuid == cu[1]).OK =
							values
							.type - 1
					} else if (values.type == 1) {
						let cu = values.mes.content.split('**/postId/**');
						this.messageList.push({
							uuid: values.uuid,
							type: 4,
							postId: values.mes.postId,
							content: cu[0],
							OK: 0,
							time: this.formatDateTime(values.mes.timestamp),
							sendTime: values.mes.timestamp
						})
					} else {
						this.messageList.push({
							uuid: values.uuid,
							type: 2,
							content: values.mes.content,
							time: this.formatDateTime(values.mes.timestamp),
							sendTime: values.mes.timestamp
						})
					}
					this.ifbottom()
					uni.$emit('trunFales', this.userid)
				}
			})
			uni.$on('backkk', values => {
				let value = JSON.parse(values)
				if (this.userid == value.userid) {
					let TTime = new Date().getTime()
					this.messageList.push({
						type: 4,
						content: value.title.title,
						time: this.formatDateTime(new Date().getTime()),
						OK: 3,
						sendTime: TTime,
						uuid: ''
					})
					uni.sendSocketMessage({
						data: JSON.stringify({
							type: 1,
							message: {
								sendTo: this.userid,
								postId: value.mesid,
								content: value.title.title + '**/postId/**' + value.mesid,
								timestamp: TTime
							}
						})
					})
					uni.$emit('sendmsg', {
						userid: this.userid,
						content: '[发送邀请]',
						time: new Date().getTime()
					})
					this.ifbottom()
				}
			})
			this.$nextTick(async () => {
				await this.gethistory(); // 等待获取历史消息完成
			})
		},
		methods: {

			isPastThreeDays(timestamp) {
				// 将时间戳转换为日期对象
				var timestampDate = new Date(timestamp);

				// 获取当前时间
				var currentDate = new Date();

				// 计算时间差
				var timeDifference = currentDate.getTime() - timestampDate.getTime();

				// 将时间差转换为天数
				var daysDifference = timeDifference / (1000 * 3600 * 24);

				// 检查时间差是否大于三天
				if (daysDifference > 3) {
					return true;
				} else {
					return false;
				}
			},
			goback() {
				this.ifclose = false
				uni.navigateBack()
			},
			Agree(value) {
				uni.sendSocketMessage({
					data: JSON.stringify({
						type: 2,
						message: {
							sendTo: this.userid,
							postId: value.postId,
							content: value.content + '**/uuid/**' + value.uuid,
							timestamp: new Date().getTime(),
						}
					})
				})
				uni.$emit('sendmsg', {
					userid: this.userid,
					content: '[回复]',
					time: new Date().getTime()
				})
				this.messageList.find(item => item == value).OK = 1
			},
			Refuse(value) {
				uni.sendSocketMessage({
					data: JSON.stringify({
						type: 3,
						message: {
							sendTo: this.userid,
							postId: value.postId,
							content: value.content + '**/uuid/**' + value.uuid,
							timestamp: new Date().getTime()
						}
					})
				})
				uni.$emit('sendmsg', {
					userid: this.userid,
					content: '[回复]',
					time: new Date().getTime()
				})
				this.messageList.find(item => item == value).OK = 2
			},
			inscroll(event) {
				uni.createSelectorQuery().in(this).select('.contain').fields({
					size: true,
					scrollOffset: true,
					scrollHeight: true,
					clientHeight: true,
				}, (rect) => {
					this.scrollHeight = rect.scrollHeight;
					this.clientHeight = rect.height;
				}).exec();
				this.scrollTop = event.detail.scrollTop;
			},
			ifbottom() {
				if (this.scrollHeight - this.scrollTop <= 1.5 * this.clientHeight) {
					// this.bot = `mes_${this.messageList.length-1}`
					setTimeout(() => {
						let contain = document.querySelector(`#mes_${this.messageList.length-1}`)
						if (contain != null) {
							contain.scrollIntoView(false, {
								behavior: "smooth"
							})
						}
					}, 0)

				}
			},
			FocusEvent(event) {},
			sendMsg() {
				if (this.msg == '') {
					uni.showToast({
						title: '请勿发送空消息！',
						icon: 'none', //如果要纯文本，不要icon，将值设为'none'
						duration: 700
					})
					return
				}
				let TTime = new Date().getTime()
				uni.sendSocketMessage({
					data: JSON.stringify({
						type: "0",
						message: {
							sendTo: this.userid,
							content: this.msg,
							timestamp: TTime
						}
					}),
					success: (res) => {
						let data = {
							type: '0', //0是我的文字，1是我的图片，2是对方文字，3是对方图片
							content: this.msg,
							time: this.formatDateTime(new Date().getTime()),
							sendTime: TTime,
							uuid: ''
						}
						this.messageList.push(data)
						uni.$emit('sendmsg', {
							userid: this.userid,
							content: this.msg,
							time: new Date().getTime()
						})
						this.msg = ''
						this.ifbottom()
					},
					fail: (err) => {
						uni.showToast({
							title: '发送失败',
							duration: 1000
						})
					}
				});
			},
			InputFocus(e) {
				this.setData({
					InputBottom: e.detail.height,
				});
			},
			InputBlur(e) {
				this.setData({
					InputBottom: 0
				});
			},
			postInvite() {
				uni.$emit('showList', this.userid)
			},
			findLast(callback) {
				for (let i = this.messageList.length - 1; i >= 0; i--) {
					if (callback(this.messageList[i], i, this.messageList)) {
						return this.messageList[i];
					}
				}
				return undefined;
			},
			gethistory() {
				this.mo_con = '···'
				let data = {
					offset: this.messageList.length,
					limit: 20,
					userId: this.userid
				}
				getHistory(data).then(res => {
					let addNum = 0
					res.data.data.rows.forEach(item => {
						if (item.msgFrom == this.userid) { //对方的
							if (item.content.startsWith('**/img/**')) { //图片
								this.messageList.unshift({
									type: 3,
									content: item.content.substring(9),
									time: this.formatDateTime(item.sendTime),
									sendTime: item.sendTime,
									uuid: item.uuid
								})
								addNum++
							} else if (item.type == 2 || item.type == 3) {
								let cu = item.content.split('**/uuid/**');
								this.rebackMes.push({
									title: cu[0],
									type: item.type,
									uuid: item.uuid,
									answear: cu[1],
									sendTime: item.sendTime
								})
							} else if (item.type == 1) {
								addNum++
								// let [content,postId]=item.content.split('**/postId/**')
								console.log(item.content.split('**/postId/**')[0])
								let temp = this.rebackMes.find(it => item.uuid == it.answear)

								if (temp) {
									console.log('找到了')
									console.log(temp)
									// this.rebackMes=this.rebackMes.filter(item=>item!=temp)
									this.messageList.unshift({
										postId: item.content.split('**/postId/**')[1],
										type: 4,
										content: item.content.split('**/postId/**')[0],
										OK: temp.type - 1,
										time: this.formatDateTime(item.sendTime),
										sendTime: item.sendTime,
										uuid: item.uuid
									})

									this.rebackMes.filter(item => item != temp)
								} else {
									addNum++

									this.messageList.unshift({
										postId: item.content.split('**/postId/**')[1],
										type: 4,
										content: item.content.split('**/postId/**')[0],
										OK: this.isPastThreeDays(item.sendTime) ? 4 : 0,
										time: this.formatDateTime(item.sendTime),
										sendTime: item.sendTime,
										uuid: item.uuid
									})

								}
							} else {
								addNum++
								this.messageList.unshift({
									type: 2,
									content: item.content,
									sendTime: item.sendTime,
									time: this.formatDateTime(item.sendTime),
								})

							}
						} else { //我的
							if (item.content.startsWith('**/img/**')) { //图片
								addNum++
								this.messageList.unshift({
									type: 1,
									content: item.content.substring(9),
									time: this.formatDateTime(item.sendTime),
									sendTime: item.sendTime
								})
							} else if (item.type == 2 || item.type == 3) {
								let cu = item.content.split('**/uuid/**');
								this.rebackMes.push({
									title: cu[0],
									type: item.type,
									sendTime: item.sendTime,
									uuid: item.uuid,
									answear: cu[1]
								})
							} else if (item.type == 1) {
								addNum++
								let temp = this.rebackMes.find(it => item.uuid == it.answear)
								if (temp) {
									// this.rebackMes=this.rebackMes.filter(item=>item!=temp)
									this.messageList.unshift({
										type: 4,
										content: item.content.split('**/postId/**')[0],
										OK: temp.type - 1,
										time: this.formatDateTime(item.sendTime),
										sendTime: item.sendTime,
										postId: item.content.split('**/postId/**')[1],
										uuid: item.uuid
									})
									this.rebackMes.filter(item => item != temp)
								} else {
									console.log('看看这这这' + this.isPastThreeDays(item.sendTime))
									this.messageList.unshift({
										type: 4,
										content: item.content.split('**/postId/**')[0],
										postId: item.content.split('**/postId/**')[1],
										OK: this.isPastThreeDays(item.sendTime) ? 4 : 3,
										time: this.formatDateTime(item.sendTime),
										sendTime: item.sendTime,
										uuid: item.uuid
									})
								}
							} else {
								this.messageList.unshift({
									type: 0,
									content: item.content,
									time: this.formatDateTime(item.sendTime),
									sendTime: item.sendTime,
									uuid: item.uuid
								})
							}
						}
					})
					this.mo_con = '查看更多'
					if (this.ifFrist) {
						setTimeout(() => {
							if (this.iffrist) {
								console.log()
								let contain = document.querySelector(`#mes_${this.messageList.length-1}`)
								contain.scrollIntoView(false)
								this.iffrist = false
							}
						})
						this.ifFrist = false
					} else {
						this.bot = `mes_${addNum}`
					}
					if (res.data.data.total <= this.messageList.length) {
						this.more = false
					} else {
						this.more = true
					}
				}).catch(err => {
					console.log(err)
				})
			},
			formatDateTime(dateTimeString) {
				// 创建 Date 对象
				const dateTime = new Date(dateTimeString);
				// 提取年、月、日、时、分、秒
				const year = dateTime.getFullYear();
				const month = (dateTime.getMonth() + 1).toString().padStart(2,
					'0'); // 月份是从 0 开始的，所以需要加 1
				const day = dateTime.getDate().toString().padStart(2, '0');
				const hours = dateTime.getHours().toString().padStart(2, '0');
				const minutes = dateTime.getMinutes().toString().padStart(2, '0');
				const seconds = dateTime.getSeconds().toString().padStart(2, '0');
				// 构建所需的格式
				const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}`;
				return formattedDateTime;
			},
			getimg() {
				uni.chooseImage({
					// count: 6, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						// uni.showLoading({
						// 	title: '发送中...'
						// })
						res.tempFilePaths.forEach((item, index) => {
							uploadimg(item).then(res => {
								let re = JSON.parse(res)
								let TTime = new Date().getTime()
								this.messageList.push({
									type: 1,
									content: re.data,
									time: this.formatDateTime(
										new Date()
										.getTime()),
									sendTime: TTime,
									uuid: ''
								})
								this.ifbottom()

								uni.sendSocketMessage({
									data: JSON.stringify({
										type: "0",
										message: {
											sendTo: this
												.userid,
											content: '**/img/**' + re.data,
											timestamp: TTime
										}
									}),
								})
								uni.$emit('sendmsg', {
									userid: this.userid,
									content: '[图片]',
									time: new Date().getTime()
								})
							}).catch(err => {
								console.log(err)
							})
						})
					},
					fail: (err) => {
						console.log(err)
					}
				});
			},
		}
	};
</script>